package com.loan.inceptor;
import com.jfinal.aop.Interceptor;
import com.jfinal.aop.Invocation;
import com.jfinal.core.Controller;
import com.jfinal.kit.Ret;
import com.loan.model.User;
import com.loan.service.TokenService;
import com.loan.util.Json;
import com.loan.util.Str;

public class TokenInceptor implements Interceptor {
	private static TokenService token = new TokenService();
	@Override
	public void intercept(Invocation inv) {
		Controller c = inv.getController();
		c.getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		String tk = c.getPara("token",""); 
		Ret ret = token.checkToken(tk);
		if(Str.nb(tk)) {
			if(ret.isOk()){
				User u = token.findUserByToken(tk);
				c.setAttr("user", u);
				c.setAttr("cid", u.getCid());
				inv.invoke();
			}else{ 
				c.renderJson(Json.error(ret.getStr("msg")));
			}
		}else{
			c.renderJson(Json.error("TOKEN不可为空！"));
		}
	}
}